package com.tsu.mall.admin.controller;


import com.tsu.mall.common.entity.Attachment;
import com.tsu.mall.common.service.IAttachmentService;
import com.tsu.mall.common.VO.LayuiTableVO;
import com.tsu.mall.common.VO.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.transform.Result;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tttttt
 * @since 2023-03-17
 */
@Controller
@RequestMapping("/attachment")
public class AttachmentController {

    @Autowired
    private IAttachmentService iAttachmentService;
    @PostMapping("/avatar")
    @ResponseBody
    public synchronized LayuiTableVO upload(MultipartFile file){
        String fileName=System.currentTimeMillis()+".png";
        File f=new File("D:/test/"+fileName);
        try {
            file.transferTo(f);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        LayuiTableVO vo=new LayuiTableVO();
        String s="/upload/"+fileName;//生成图片地址

        Attachment attachment=new Attachment();
        attachment.setAvatar(s);//设置图片地址
        attachment.setSource("wares");//源
        attachment.setCreateTime(LocalDateTime.now());//上传时间
        attachment.setFileName(file.getOriginalFilename());//原文件名
        attachment.setType(file.getContentType());//类型
        attachment.setFileSize(file.getSize());//文件大小
        iAttachmentService.insert(attachment);//将本次上传的图片的地址保存到数据库中
        vo.setData(attachment);
        return vo;
    }

    @PostMapping("/delete")
    @ResponseBody
    public ResultVO deleteAttachment(Integer id){
        ResultVO vo = new ResultVO();
        iAttachmentService.removeById(id);
        vo.setMsg("删除图片成功!");
        return vo;
    }

}
